package edu.nf.db.util.convertor;

import edu.nf.db.util.TypeConvertor;

import java.sql.Time;
import java.sql.Timestamp;
import java.time.*;
import java.util.Date;

/**
 * 将数据库不同类型的日期统一转换为 java.util.Date 类或者是它的子类
 *
 * @author zhu
 * @date 2024-05-09
 */
public class DateConvertor implements TypeConvertor {
    @Override
    public Object convert(Class<?> fieldType, Object value) {
        String typeName = fieldType.getName();
        long time = getTime(value);
        return switch (typeName) {
            case "java.util.Date" -> new Date(time);
            case "java.sql.Date" -> new java.sql.Date(time);
            case "java.sql.Time" -> new Time(time);
            case "java.sql.Timestamp" -> new Timestamp(time);
            default -> throw new IllegalArgumentException("Invalid type " + typeName);
        };
    }

    @Override
    public boolean supports(Class<?> type) {
        // 获取 type 的全限定类名
        String typeName = type.getName();

        return switch (typeName) {
            case "java.util.Date",
                 "java.sql.Date",
                 "java.sql.Time",
                 "java.sql.Timestamp" -> true;
            default -> false;
        };
    }

    /**
     * 将日期都变成 long 的类型
     *
     * @param value 要转换的值
     * @return 返回 long 值
     */
    private long getTime(Object value){
        return switch (value) {
            case Date date -> date.getTime();
            case LocalDateTime localDateTime -> localDateTimeToDate(localDateTime).getTime();
            case LocalDate localDate -> localDateToDate(localDate).getTime();
            case LocalTime localTime -> localTimeToDate(localTime).getTime();
            default -> throw new RuntimeException("Unable to convert " + value + " to Date");
        };
    }

    private Date localDateTimeToDate(LocalDateTime localDateTime){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zoneId).toInstant();
        return Date.from(instant);
    }

    private Date localDateToDate(LocalDate localDate){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = localDate.atStartOfDay(zoneId).toInstant();
        return Date.from(instant);
    }

    private Date localTimeToDate(LocalTime localTime){
        ZoneId zoneId = ZoneId.systemDefault();
        Instant instant = localTime.atDate(LocalDate.now()).atZone(zoneId).toInstant();
        return Date.from(instant);
    }
}
